package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.commons.entities.Result;
import com.atguigu.springcloud.entities.Dept;
import com.atguigu.springcloud.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.zalando.logbook.Logbook;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author horay
 * @category Class description
 * @email horay_hyc@qq.com
 * @date 2018/6/9 17:41
 */
@Slf4j
@RestController
public class DeptController {

    @Autowired
    private DeptService deptService;

    @Autowired
    private DiscoveryClient discoveryClient;

    @PostMapping("/dept")
    public Result add(@RequestBody Dept dept) {
        Integer count = deptService.add(dept);
        return Result.ok();
    }

    @PutMapping("/dept")
    public Result edit(@RequestBody Dept dept) {
        Integer count = deptService.edit(dept);
        return Result.ok();
    }

    @DeleteMapping("/dept/{deptNo}")
    public Result delete(@PathVariable Long deptNo) {
        Integer count = deptService.delete(deptNo);
        return Result.ok();
    }

    @GetMapping("/dept/{deptNo}")
    public Result get(@PathVariable Long deptNo) {
        Dept dept = deptService.getByDeptNo(deptNo);
        if (Objects.isNull(dept)) {
            throw new RuntimeException("dept not found");
        }
        return Result.ok(dept);
    }

    @GetMapping("/dept")
    public Result find() {
        List<Dept> list = deptService.findAll();
        return Result.ok(list);
    }

    @GetMapping("/discovery")
    public Result discovery() {
        List<String> services = discoveryClient.getServices();
        services.stream().forEach(service -> {
            log.info("servcie={}", service);
        });

        List<ServiceInstance> instances = discoveryClient.getInstances("microservicecloud-dept");
        instances.stream().forEach(instance -> {
            log.info("instance={}", instance.getUri());
        });

        Map<String, Object> map = new HashMap<String, Object>(2);
        map.put("services", services);
        map.put("serviceInstance", instances);
        return Result.ok(map);
    }

}
